package io.wongd.lib_douyin

import android.content.Context
import android.provider.Settings
import io.wongd.lib_douyin.util.DownloadUtil
import io.wongd.lib_douyin.util.T
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.withContext
import org.json.JSONObject
import org.jsoup.Jsoup

object DouyinSimple {

    fun init(ctx: Context) {
        T.init(ctx)
        DownloadUtil.init(ctx)
    }

    fun getAndroidID(context: Context): String {
        return Settings.System.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
    }

    val douyinScope by lazy { CoroutineScope(Dispatchers.IO + SupervisorJob()) }

    suspend fun <T> main(block: suspend CoroutineScope.() -> T): T {
        return withContext(Dispatchers.Main) { return@withContext block() }
    }

    suspend fun <T> io(block: suspend CoroutineScope.() -> T): T {
        return withContext(Dispatchers.IO) { return@withContext block() }
    }

    var cookie: String = ""

    val douyinHeaders: MutableMap<String, String>
        get() {
            val headers: MutableMap<String, String> = HashMap()
            headers["user-agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41"
            return headers
        }

    val userAgent: String get() = douyinHeaders["user-agent"]!!

    private fun redirect(url: String): String? {
        val response = Jsoup.connect(url).headers(douyinHeaders).response()
        return response.header("location")
    }

    fun getItemId(copyInfo: String): String {
        var itemIds = ""
        var url = copyInfo
        // 短地址或者口令
        if (!copyInfo.contains("https://www.douyin.com/video/")) {
            val shortUrl = "https://v.douyin.com/${copyInfo.split("https://v.douyin.com/")[1]}"
            url = redirect(shortUrl) ?: return ""

        } else {
            itemIds = url.split("/video/")[1]
        }
        return itemIds
    }

    fun getFileData(ids: String) {
        val json_url = "https://m.douyin.com/web/api/v2/aweme/iteminfo/?a_bogus=&item_ids=${ids}"
        val response = Jsoup.connect(json_url).headers(douyinHeaders).response()
        val respStr = response.body()
        val data: JSONObject = JSONObject(respStr).optJSONArray("item_list").getJSONObject(0)

        val desc = data.optString("desc").replace("\n", "")  // 描述
        val create_time = data.optString("create_time")  // 发布时间,这里取日期
        val author = data.optJSONObject("author").optString("nickname")  // 作者

        // 获取下载链接
        val ___file_url = data.optJSONObject("video").optJSONObject("play_addr").optJSONArray("url_list").getString(0)
        // 去水印
        val __file_url = ___file_url.replace("playwm/", "/play/")
        // 720p改成1080p
        val _file_url = __file_url.replace("ratio=720p", "ratio=1080p")
        // 重定向下载链接
        val file_url = redirect(_file_url)
    }


}